/*********************************************************
 (x,y)        : LED position
  dt          : time minimum morse code gap (in frame unit)
  v_threshold : the brightness limit of LED ON state
  one_word    : one morse code
  lineHeight  : morse code row gap
**********************************************************/
x=133;y=293;
dt = 1.8;
v_threshold = 240;
lineHeight  =18;
wordArray = newArray();
one_word = "";
wordCount = 0;

setLineWidth(3);
lastFrameHigh=0;
lastFrameLow=0;
drawArray = newArray();

for(i=138;i<915;i++){

  setSlice(i);
  v = getValue(x, y);

  if(v>v_threshold){
    if(getSliceNumber()-lastFrameHigh>dt*3){//a long gap

      //print(one_word);
      wordArray = Array.concat(wordArray,one_word);
      one_word="";
      drawArray = Array.concat(drawArray,-1);
      wordCount++;
    }
    //Overlay.drawLine(x+x_offset,y_offset,x+x_offset,y_offset);
    drawMorse(drawArray);
    drawArray = Array.concat(drawArray,1);
    lastFrameHigh=getSliceNumber();

  }else{
    if(getSliceNumber()-lastFrameLow>dt &&
       getSliceNumber()-lastFrameLow<dt*5){
      one_word=one_word+".";
    }    
    if(getSliceNumber()-lastFrameLow>dt*5){
      one_word=one_word+"-";
    }

    lastFrameLow=getSliceNumber();
    drawArray = Array.concat(drawArray,0);
  }

  wait(30);

}

  function drawMorse(draw_array){
    Overlay.clear();
    n = draw_array.length;
    xoffset = 0;yoffset=0;
    word_idx = 0;
    for(i=0;i<n;i++){
      xt=x+xoffset*2.5;yt=y-5-wordCount*lineHeight+yoffset;
      if(draw_array[i]==1){
        Overlay.drawLine(xt,yt,xt+2,yt);
      }else
      if(draw_array[i]==-1){
        xoffset = 0;
        yoffset +=lineHeight;

        drawText(wordArray[word_idx],x-10,yt);
        word_idx++;
      }
      xoffset++;
    }
   Overlay.show();
   updateDisplay();
    
  }

  function drawText(txt,x,y) {
    setColor("yellow");
    size = 38 *getWidth/512;
    setFont("SansSerif", size);
    a = decode(txt);
    Overlay.drawString(a, x, y);
  }

  function decode(code){
    if(code==".----")return "1";
    if(code=="..---")return "2";
    if(code=="...--")return "3";
    if(code=="....-")return "4";
    if(code==".....")return "5";
    if(code=="-....")return "6";
    if(code=="--...")return "7";
    if(code=="---..")return "8";
    if(code=="----.")return "9";
    if(code=="-----")return "0";
    return "";
  }
